﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using System.Collections;

namespace logicunivesityinventorystore.Department
{
    public partial class MakeOrder : System.Web.UI.Page
    {
        List<OrderItem> orderItems ;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                orderItems = new List<OrderItem>();
                btnSubmit.Visible = false;
                SetVisibility(false,false); 

            }
           
            DateTime date1 = DateTime.Now.Date;
            int today = Convert.ToInt32(date1.DayOfWeek);
            int duration=(7-today)+7;
            cal1.StartDate = date1.AddDays(duration);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            orderItems = (List<OrderItem>)Session["orderItems"];
            if(gvOrderItems.Rows.Count>0)
            foreach (GridViewRow gvRow in gvOrderItems.Rows)
            {
                string itemCodes = gvRow.Cells[0].Text;
                try
                {
                    OrderItem orItem = orderItems.Find(ord => ord.ItemCode == itemCodes);
                    orItem.Quantity = Convert.ToInt32((gvRow.FindControl("txtQty") as TextBox).Text);
                }
                catch (Exception ee)
                { }
            }
            btnSubmit.Visible = true;
            string itemCode = ddlItem.SelectedValue;
            string categoryName = ddlCategory.SelectedItem.Text;
            string itemName = ddlItem.SelectedItem.Text;
            int qty =Convert.ToInt32(txtQty.Text);
            ItemFacade item = new ItemFacade();
            int reorderqty = item.FindByItemID(itemCode).ReorderQty;

            if (qty > reorderqty)
            {
                ScriptManager.RegisterStartupScript(
           this,
           this.GetType(),
           "MessageBox",
           "alert('Quantity is too large. Please consider making Special Order as we might not be able to fulfill your request this week.');",
           true);
            }
            OrderItem orderItem = new OrderItem(itemCode, categoryName, itemName, qty);
            OrderItem itm = orderItems.Find(ords => ords.ItemCode == orderItem.ItemCode);
            
            if (itm != null)
            {
                itm.Quantity = itm.Quantity + qty;
            }
            else
            {
                orderItems.Add(orderItem);
            }

            BindGrid();
            txtQty.Text = "1";
            if (ddlOrderType.SelectedItem.Text.Equals("Special Order"))
            {
                SetVisibility(true, true);
            }
            else
            {
                SetVisibility(false, false);
 
            }
        }

        private void BindGrid()
        {
            Session["orderItems"] = orderItems;
            gvOrderItems.DataSource = orderItems;
            gvOrderItems.DataBind();
        }

        protected void gdOrderItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
                int index = 0;
                orderItems = (List<OrderItem>)Session["orderItems"];
                foreach (OrderItem or in orderItems)
                {
                    if (or.ItemCode == e.CommandArgument.ToString())
                    {
                        orderItems.RemoveAt(index);
                        break;
                    }
                    index++;
                }
                
                BindGrid();
                if (gvOrderItems.Rows.Count == 0)
                {
                    btnSubmit.Visible = false;
                    lbRemark.Visible = false;
                    txtRemark.Visible = false;
 
                }
 
            }
            
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
           
            Requisition req = new Requisition();
            req.EmployeeID = User.Identity.Name;
           
            req.Status = "Pending";
            req.RequisitionDate = DateTime.Now.Date;
            if (ddlOrderType.SelectedItem.Text.Equals("Special Order"))
            {
                req.ExpectedDate = Convert.ToDateTime(txtExDate.Text);
            }
            else
            {
                req.ExpectedDate = DateTime.Now.Date;
            }
            req.Remarks = txtRemark.Text;
            int count =( (List<OrderItem>)Session["orderItems"]).Count;
            RequisitionDetail[] reqDetails=new RequisitionDetail[count];
            int index = 0;
            string newFormID = new RequisitionFacade().GetFormID(req.EmployeeID);
            req.FormID = newFormID;
            foreach(OrderItem order in (List<OrderItem>)Session["orderItems"])
            {
                RequisitionDetail requ=new RequisitionDetail();
                requ.FormID = newFormID;
                requ.ItemCode=order.ItemCode;
                requ.Qty=order.Quantity;
                reqDetails[index] = requ;
                index++;
            }
            new RequisitionFacade().insertRequisition(req, req.EmployeeID, reqDetails);

            Response.Redirect("HomePage_Department.aspx");
        }

        

        private void SetVisibility(bool status,bool status1)
        {

            
            lblExDate.Visible = status;
            lbRemark.Visible = status1;
            txtExDate.Visible = status;
            txtRemark.Visible = status1;
          
        }

        protected void ddlOrderType_SelectedIndexChanged1(object sender, EventArgs e)
        {
            if (ddlOrderType.SelectedItem.Text.Equals("Special Order"))
            {
                ScriptManager.RegisterStartupScript(this,
                this.GetType(),
                "AlertScript",
                "alert('Special order will be processed 2 weeks later!');",
                 true);
                SetVisibility(true,false);
            }
            else
            {
                SetVisibility(false,false);
            }
        }
    }
}